//定义组合式API仓库
import { defineStore } from "pinia";
import type { loginFormData, loginResponseData, userInfoReponseData } from '@/api/user/type.ts'
import type { UserState } from './types/type'
import { userLoginwsb, userInfo, reqLogout, userTestLogin } from '@/api/user/index.ts'
// 引入常量路由以及动态路由
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes.ts'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
import router from '@/router'

//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
// 用于过滤当前用户所需要的展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
    return asyncRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}
let loginStore = defineStore('userLogin', {
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
            menuRoutes: constantRoute,
            username: '',
            avatar: '',
        }

    },
    actions: {
        // 这个真是项目登录操作接口
        async userLogin(data: loginFormData) {
            let result: loginResponseData = await userLoginwsb(data)
            if (result.code == 200) {
                this.token = (result.data as String)
                //pinia仓库存储一下token
                //由于pinia|vuex存储数据其实利用js对象
                SET_TOKEN((result.data as String))
                return 'ok'
            } else {
                return Promise.reject(new Error(result.data))
            }

        },
        // 这是测试登录的接口
        // async userLogin(data: any) {
        //     let result = await userTestLogin(data)
        //     console.log(result.code, '王');
        //     if (result.code == 200) {
        //         this.token = (result.data.token as String)
        //         SET_TOKEN((result.data.token as String))
        //         return 'ok'
        //     } else {
        //         return Promise.reject(new Error(result.message))
        //     }
        // },

        //   获取用户个人信息操作
        async userInfo() {
            let result: userInfoReponseData = await userInfo()
            console.log(result, '用户个人信息');
            if (result.code == 200) {
                this.username = result.data.name;
                this.avatar = result.data.avatar;
                let userAsyncRoute: Array<any> = filterAsyncRoute(cloneDeep(asyncRoute), result.data.routes)
                this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
                // 目前的路由器管理的只有常量路由，用户计算完毕异步的路由、任意路由动态的去追加
                const userAllRoutes = [...userAsyncRoute, anyRoute]
                localStorage.setItem('userAllRoutes', JSON.stringify(this.menuRoutes))
                userAllRoutes.forEach((item: any) => {
                    router.addRoute(item)
                })

                return 'ok'
            } else {
                return Promise.reject(new Error(result.message));
            }



        },
        // 退出登录操作
        async userLoginOut() {
            let result: any = await reqLogout()
            //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
            if (result.code == 200) {
                this.token = '';
                this.username = '';
                this.avatar = '';
                REMOVE_TOKEN()
                return "ok"
            } else {
                return Promise.reject(new Error(result.message));
            }

        }
    }
})
export default loginStore;